/**
 *
 * @author 
 *
 */
class BaseProtobufSocket extends egret.EventDispatcher{
    
    //上下文
    private packetContext: any;

    //封包类型
    private packetClass: any;
    
    //数据段索引
    private messageByType: Object;
    private messageByID: Object;
    private messageByName: Object;
    
    //----------------------------------------------------------------------------------------
    
    
    //通信功能
    private webSocket: egret.WebSocket;
    
    //-----------------------------------------------------------------------------------------------
    

	public constructor() {
    	  super();
        //初始化通信
        this.webSocket = new egret.WebSocket();
        this.webSocket.type = egret.WebSocket.TYPE_BINARY;
        this.webSocket.addEventListener(egret.ProgressEvent.SOCKET_DATA,this.onReceiveMessage,this);
        this.webSocket.addEventListener(egret.Event.CONNECT,this.onSocketOpen,this);
        this.webSocket.addEventListener(egret.Event.CLOSE,this.onSocketClose,this);
	}
	
	
	//   protoContent protobuf描述文 
    public init(protoContent: string):void{

        //构建工厂
        var packetBuilter: any = dcodeIO.ProtoBuf.loadProto(protoContent);
        this.packetContext = packetBuilter.build("Message");
        
        //封包
        this.packetClass = this.packetContext["RemotePacket"];
        
        //反射封包  获取数据段描述
        this.messageByID = this.packetClass.$type._fieldsById;
        this.messageByName = this.packetClass.$type._fieldsByName;
        this.messageByType = new Object();
        var packetChilds = this.packetClass.$type.children;
        for(var i: number = 0;i < packetChilds.length;i++) {
            var filed: any = packetChilds[i];
            //查看是否是扩展类型   是扩展类型则放入map中
            if(filed["extension"] != null) {
                this.messageByType[filed.resolvedType.name] = filed;
            }
        }
    }
    
    public connectTo(host: string,port: number) :void{
        if(this.webSocket.connected) {
            this.webSocket.close();
        }
        this.webSocket.connect(host,port);
    }
    
    public closeConnect():void{
        if(this.webSocket.connected) {
            this.webSocket.close();
        }
    }
	
	//-------------------------------------------------------------------------------------------------------
	
    //创建一个新的指定类型的数据包
    public getNewMsgInstance(name: string): any {
        var cla: any = this.packetContext[name];
        if(cla == null) {
            return null;
        } 
        var msg: any = new cla();
        return msg;
    }
    
    //发送一个数据包  使用封包结构
    public sendMsgWithPacket(msg: any): void {
        var name = msg.__proto__.$type.name;
        var type: any = this.messageByType[name];
        if(type == null) {
            return null;
        }
        var packet: any = new this.packetClass();
        packet.set("type",type.id);
        packet.set(type.name,msg);
        
        var arraybuffer: ArrayBuffer = packet.encode().toArrayBuffer();
        var btyearray: egret.ByteArray = new egret.ByteArray(arraybuffer);
        this.webSocket.writeBytes(btyearray);
        this.webSocket.flush();
        console.log("socket req: "+name);
    }
    
    
    
    //-----------------------------------------------------------------------------------------------------
    
    private onReceiveMessage(event: ProgressEvent): void {
        var bytearray: egret.ByteArray = new egret.ByteArray();
        this.webSocket.readBytes(bytearray);
        
        var packet: any = this.packetClass.decode(bytearray.buffer);
        var typeID: number = packet.get("type");
        var type = this.messageByID[typeID];
        
        var name: string = type.resolvedType.name;
        var msg: any = packet.get(type.name);
        this.onMessageReceived(name,msg);
    }
    
    

    public onSocketOpen(event: Event): void {
        console.log("游戏服务器连线成功");
    }

    public onSocketClose(event: Event): void {
        console.log("游戏服务器连线中断");
    }
    
    public onMessageReceived(name:string,msg:any):void{
        console.log("游戏服务器发来消息：" + name);
    }
}
